package com.atguigu.jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/*
    工具类
 */
public class JDBCUtils {
    static String username;
    static String pwd;
    static String url;
    static String driverClass;
    static{
        InputStream fis = null;
        try {
        //一 读取配置文件内容
        //1.创建Properties的对象
        Properties p = new Properties();
        //2.创建流 - 文件输入流
        //默认目录：项目的根目录下（编译后的项目）
        fis = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        //3.加载流
        p.load(fis);
        //4.读取文件中的内容
         username = p.getProperty("username");
         pwd = p.getProperty("pwd");
         url = p.getProperty("url");
         driverClass = p.getProperty("driverClass");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //5.关资源
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Connection getConnection(){
        try {
            //二 获取连接对象
            //1.Drvier类进行类加载
            Class.forName(driverClass);
            //3.获取连接对象
            Connection connection = DriverManager.getConnection(url, username, pwd);
            return connection;
        }catch (Exception e){
            e.printStackTrace();
            //终止程序 --- 将编译时异常转换成运行时异常
            throw new RuntimeException(e.getMessage());
        }

    }

    public static void close(PreparedStatement ps,Connection connection){
        if (ps != null){
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(connection != null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void close(PreparedStatement ps, Connection connection, ResultSet rs) {
        close(ps,connection);
        if (rs != null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
